
package com.epam.android.training.level1.util;

import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Anton Novikov
 */
public final class DateUtils {
  private static final String TAG = DateUtils.class.getSimpleName();

  private static final List<SimpleDateFormat> SUPPORTED_FORMATS = new ArrayList<SimpleDateFormat>();

  private static final SimpleDateFormat DEFAULT_FORMAT = new SimpleDateFormat(
      "dd MMM yyyy HH:mm:ss");

  private static final SimpleDateFormat DEFAULT_DATE_FORMAT = new SimpleDateFormat("dd MMM yyyy");

  private static final SimpleDateFormat DEFAULT_TIME_FORMAT = new SimpleDateFormat("HH:mm:ss");

  static {
    // RFC-822 spec
    SUPPORTED_FORMATS.add(new SimpleDateFormat("EEE, dd MMM yy HH:mm:ss z"));
    SUPPORTED_FORMATS.add(new SimpleDateFormat("EEE, dd MMM yy HH:mm:ss Z"));
    SUPPORTED_FORMATS.add(new SimpleDateFormat("EEE, dd MMM yy HH:mm z"));
    SUPPORTED_FORMATS.add(new SimpleDateFormat("EEE, dd MMM yy HH:mm Z"));
    SUPPORTED_FORMATS.add(new SimpleDateFormat("dd MMM yy HH:mm:ss z"));
    SUPPORTED_FORMATS.add(new SimpleDateFormat("dd MMM yy HH:mm:ss Z"));
    SUPPORTED_FORMATS.add(new SimpleDateFormat("dd MMM yy HH:mm z"));
    SUPPORTED_FORMATS.add(new SimpleDateFormat("dd MMM yy HH:mm Z"));

    // default format used to convert from date to string
    SUPPORTED_FORMATS.add(DEFAULT_FORMAT);
    SUPPORTED_FORMATS.add(DEFAULT_DATE_FORMAT);
    SUPPORTED_FORMATS.add(DEFAULT_TIME_FORMAT);
  }

  /**
   * Creates an instance of DateUtils.
   */
  private DateUtils() {}

  public static Date parseDate(String strDate) {
    if (StringUtils.isEmpty(strDate)) {
      return null;
    }
    strDate = strDate.trim();
    for (SimpleDateFormat format : SUPPORTED_FORMATS) {
      try {
        return format.parse(strDate);
      } catch (ParseException e) {
        // do nothing. just try another supported formatter.
        continue;
      }
    }
    // if no one formatter can parse the date, just return null;
    Log.w(TAG, "Unable to find appropriate parser among supported.");
    return null;
  }

  public static String formatDateTime(Date date) {
    return DEFAULT_FORMAT.format(date);
  }

  public static String formatDate(Date date) {
    return DEFAULT_DATE_FORMAT.format(date);
  }

  public static String formatTime(Date date) {
    return DEFAULT_TIME_FORMAT.format(date);
  }
}
